import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    """合并购物车"""

    # 先获取cookie
    cart_str = request.COOKIES.get('cart')
    # 判断cookie是否有数据
    # 如果cookie没有购物车数据 直接return
    if cart_str is None:
        return
    # 把cookie购物车的字符串 转换成字典
    cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
    # 创建redis连接对象
    redis_conn = get_redis_connection('cart')
    pl = redis_conn.pipeline()
    # 遍历cookie购物车大字典,把sku_id及count想redis的hash中存储
    for sku_id in cart_dict:
        pl.hset('cart_%s' % user.id, sku_id, cart_dict[sku_id]['count'])
        if cart_dict[sku_id]['selected']:
            # 如果cookie勾选了商品，直接把勾选的商品id存到redis中
            pl.sadd('selected_%s' % user.id, sku_id)
    pl.execute()
    # 删除cookie购物车数据
    response.delete_cookie('cart')



